package com.nami.gate.process.upmsg;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.json.JSONUtil;
import com.nami.gate.config.RpcConfig;
import com.nami.gate.external.basic.constants.UpTopicConst;
import com.nami.gate.external.basic.request.upmsg.UpMsgLogoutRequest;
import com.nami.gate.middleware.mq.MqSender;
import com.nami.im.network.model.packet.v2.Packet;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.dubbo.common.utils.NetUtils;
import org.jetbrains.annotations.NotNull;

import java.net.InetSocketAddress;


/**
 * 描述：
 *
 * @Author: lbc
 * @Date: 2023-07-16 16:41
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
public class LogoutProcess implements PacketProcessor {

    private MqSender mqSender;
    private RpcConfig rpcConfig;

    public LogoutProcess(MqSender mqSender, RpcConfig rpcConfig) {
        this.mqSender = mqSender;
        this.rpcConfig = rpcConfig;
    }

    /**
     * logic 发送rpc消息到channel 异步执行
     *
     * @param channel
     * @param packet
     */
    @Override
    public void process(Channel channel, Packet packet) throws Exception {
        TimeInterval timer = DateUtil.timer();
        InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();
        String clientIp = socketAddress.getAddress().getHostAddress();
        try {
            mqSender.send(UpTopicConst.LOGOUT_TOPIC, buildLogoutWrap(clientIp, packet));
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        log.info("[logout] 客户端【{}】请求登录处理完毕。use:{}ms", channel.remoteAddress(), timer.interval());
    }

    @NotNull
    private String buildLogoutWrap(String clientIp, Packet packet) {
        UpMsgLogoutRequest request = new UpMsgLogoutRequest();
        request.setDubboIp(NetUtils.getLocalHost());
        request.setDubboPort(rpcConfig.getDubboPort());
        request.setClientIp(clientIp);
        request.setTags(rpcConfig.getConnectId());
        log.info("[logout] request:{}", ToStringBuilder.reflectionToString(request, ToStringStyle.SHORT_PREFIX_STYLE));
        request.setPacket(packet);
        return JSONUtil.toJsonStr(request);
    }

}
